<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>仪表板</h1>
      <p class="subtitle">欢迎使用 CAR Registry 容器和制品仓库</p>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon repositories">
            <el-icon><Box /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.repositories || 0 }}</h3>
            <p>仓库总数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon artifacts">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.artifacts || 0 }}</h3>
            <p>制品总数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon storage">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ formatSize(stats.storageUsed || 0) }}</h3>
            <p>存储使用</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon downloads">
            <el-icon><Download /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.downloads || 0 }}</h3>
            <p>下载次数</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- Recent Activities -->
    <div class="dashboard-content">
      <div class="content-left">
        <el-card class="activity-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>最近活动</h3>
              <el-button type="text" @click="refreshActivities">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          
          <div v-loading="activitiesLoading" class="activities-list">
            <div v-if="activities.length === 0" class="empty-state">
              <el-icon><DocumentRemove /></el-icon>
              <p>暂无活动记录</p>
            </div>
            
            <div v-else>
              <div 
                v-for="activity in activities" 
                :key="activity.id" 
                class="activity-item"
              >
                <div class="activity-icon">
                  <el-icon v-if="activity.action === 'push'" class="push-icon"><Upload /></el-icon>
                  <el-icon v-else-if="activity.action === 'pull'" class="pull-icon"><Download /></el-icon>
                  <el-icon v-else class="default-icon"><Operation /></el-icon>
                </div>
                <div class="activity-content">
                  <p class="activity-description">{{ activity.description }}</p>
                  <p class="activity-time">{{ formatTime(activity.createdAt) }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="content-right">
        <el-card class="repositories-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>热门仓库</h3>
              <router-link to="/repositories">
                <el-button type="text">查看全部</el-button>
              </router-link>
            </div>
          </template>
          
          <div v-loading="repositoriesLoading" class="repositories-list">
            <div v-if="popularRepositories.length === 0" class="empty-state">
              <el-icon><Box /></el-icon>
              <p>暂无仓库</p>
            </div>
            
            <div v-else>
              <div 
                v-for="repo in popularRepositories" 
                :key="repo.id" 
                class="repository-item"
                @click="goToRepository(repo.name)"
              >
                <div class="repo-info">
                  <h4>{{ repo.name }}</h4>
                  <p class="repo-description">{{ repo.description || '暂无描述' }}</p>
                  <div class="repo-stats">
                    <span class="stat">
                      <el-icon><Download /></el-icon>
                      {{ repo.downloadCount || 0 }}
                    </span>
                    <span class="stat">
                      <el-icon><Files /></el-icon>
                      {{ repo.artifactCount || 0 }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Box,
  Files,
  Coin,
  Download,
  Upload,
  Refresh,
  DocumentRemove,
  Operation
} from '@element-plus/icons-vue'
import type { SystemStats, AuditLog, Repository } from '@/types/api'

const router = useRouter()

const stats = ref<SystemStats>({
  repositories: 0,
  artifacts: 0,
  storageUsed: 0,
  downloads: 0
})

const activities = ref<AuditLog[]>([])
const popularRepositories = ref<Repository[]>([])
const activitiesLoading = ref(false)
const repositoriesLoading = ref(false)

const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatTime = (time: string): string => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes} 分钟前`
  } else if (hours < 24) {
    return `${hours} 小时前`
  } else if (days < 7) {
    return `${days} 天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const loadStats = async () => {
  try {
    // TODO: Implement API call to get system statistics
    // const response = await getSystemStats()
    // stats.value = response.data
    
    // Mock data for now
    stats.value = {
      repositories: 12,
      artifacts: 156,
      storageUsed: 2147483648, // 2GB
      downloads: 1234
    }
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  }
}

const loadActivities = async () => {
  activitiesLoading.value = true
  try {
    // TODO: Implement API call to get recent activities
    // const response = await getRecentActivities()
    // activities.value = response.data
    
    // Mock data for now
    activities.value = [
      {
        id: '1',
        action: 'push',
        description: '用户 admin 推送了 nginx:latest 到仓库',
        createdAt: new Date(Date.now() - 1000 * 60 * 30).toISOString(),
        userId: '1',
        username: 'admin'
      },
      {
        id: '2',
        action: 'pull',
        description: '用户 developer 拉取了 redis:6.2',
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
        userId: '2',
        username: 'developer'
      }
    ]
  } catch (error) {
    ElMessage.error('加载活动记录失败')
  } finally {
    activitiesLoading.value = false
  }
}

const loadPopularRepositories = async () => {
  repositoriesLoading.value = true
  try {
    // TODO: Implement API call to get popular repositories
    // const response = await getPopularRepositories()
    // popularRepositories.value = response.data
    
    // Mock data for now
    popularRepositories.value = [
      {
        id: '1',
        name: 'nginx',
        description: 'High-performance web server',
        downloadCount: 500,
        artifactCount: 12,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      {
        id: '2',
        name: 'redis',
        description: 'In-memory data structure store',
        downloadCount: 300,
        artifactCount: 8,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    ]
  } catch (error) {
    ElMessage.error('加载热门仓库失败')
  } finally {
    repositoriesLoading.value = false
  }
}

const refreshActivities = () => {
  loadActivities()
}

const goToRepository = (name: string) => {
  router.push(`/repositories/${name}`)
}

onMounted(() => {
  loadStats()
  loadActivities()
  loadPopularRepositories()
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.repositories {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.artifacts {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.storage {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.downloads {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info h3 {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.dashboard-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.activities-list,
.repositories-list {
  min-height: 300px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #c0c4cc;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.push-icon {
  background: #e1f3d8;
  color: #67c23a;
}

.pull-icon {
  background: #ecf5ff;
  color: #409eff;
}

.default-icon {
  background: #fdf6ec;
  color: #e6a23c;
}

.activity-content {
  flex: 1;
}

.activity-description {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.activity-time {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.repository-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.repository-item:hover {
  background-color: #f5f7fa;
  margin: 0 -16px;
  padding: 16px;
  border-radius: 4px;
}

.repository-item:last-child {
  border-bottom: none;
}

.repo-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.repo-description {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #909399;
}

.repo-stats {
  display: flex;
  gap: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

@media (max-width: 768px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}
</style>